package com.columboid.protocol.syncml.tests;

import java.io.StringReader;

import javax.xml.bind.JAXBException;

import junit.framework.TestCase;

import org.junit.Test;

import com.columboid.protocol.syncml.helper.JaxbHelper;
import com.columboid.protocol.syncml.representation.ObjectFactory;
import com.columboid.protocol.syncml.representation.SyncBody;
import com.columboid.protocol.syncml.representation.SyncHdr;
import com.columboid.protocol.syncml.representation.SyncML;
import com.columboid.protocol.syncml.tests.resources.SyncMLString;

public class JaxbTest extends TestCase {

	@Test
	public void testCreateXmlFromObjectWithSingleObject() throws JAXBException {
		SyncML sml = new SyncML();
		String expected = SyncMLString.getSyncMLSingleObject();
		String actual = JaxbHelper.getJaxbObjectString(sml, false);
		assertTrue(actual.equals(expected));
	}

	@Test
	public void testCreateXmlFromObjectWithOnlyHeader() throws JAXBException {

		String expected = SyncMLString.getSyncMLOnlyHeader();

		SyncML sml = new SyncML();
		SyncHdr header = new SyncHdr();
		sml.setSyncHdr(header);

		String actual = JaxbHelper.getJaxbObjectString(sml, false);

		assertTrue(actual.equals(expected));
	}

	@Test
	public void testCreateXmlFromObjectWithHeaderAndBody() throws JAXBException {

		String expected = SyncMLString.getSyncMLHeaderAndBody();
		SyncML sml = new SyncML();
		SyncHdr header = new SyncHdr();
		sml.setSyncHdr(header);
		SyncBody body = new SyncBody();
		sml.setSyncBody(body);

		String actual = JaxbHelper.getJaxbObjectString(sml, false);
		assertTrue(actual.equals(expected));
	}

	@Test
	public void testCreateXmlFromObjectWithFinalHeaderAndBody()
			throws JAXBException {
		String expected = SyncMLString.getFinalSyncMLHeaderAndBody();
		SyncML sml = new SyncML();
		SyncHdr header = new SyncHdr();
		sml.setSyncHdr(header);
		SyncBody body = new SyncBody();
		sml.setSyncBody(body);

		String actual = "";
		actual = JaxbHelper.getJaxbObjectString(sml, true);
		assertTrue(actual.equals(expected));
	}

	@Test
	public void testCreateObjectFromXml() {

		String xml = SyncMLString.getSyncMLBody();
		String xsd = JaxbHelper.getSyncMLSchema();

		StringReader xmlReader = new StringReader(xml);
		StringReader xsdReader = new StringReader(xsd);
		try {

			SyncML sml = JaxbHelper.CreateSyncMLObject(xmlReader, xsdReader,SyncML.class,ObjectFactory.class);

			assertTrue(sml != null);

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			assertTrue(false);
		} finally {
			if (xmlReader != null) {
				xmlReader.close();
				xmlReader = null;
			}

			if (xsdReader != null) {
				xsdReader.close();
				xsdReader = null;
			}

		}

	}

}
